﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Missbot.Common;
using Missbot.Core.Cache;
using Dolany.UtilityTool;
using Missbot.Core.CrossingRoute;
using Newtonsoft.Json;

namespace Missbot.AIModule.Pet.Expedition
{
    public class ExpeditionSceneSvc : IDataMgr, ISingleton, IViewable
    {
        private List<ExpeditionScene> Scenes;

        public ExpeditionScene this[string SceneName] => Scenes.FirstOrDefault(s => s.Name == SceneName);

        public readonly string[] Flavorings = { "海鲜酱油", "秘制番茄酱", "精品海盐", "风味辣酱", "蓝巧果果汁", "火桂", "龙鳞草茎" };

        public void RefreshData()
        {
            Scenes = ExpeditionSceneDA.GetAll();
        }

        public IEnumerable<ExpeditionScene> TodayExpedition()
        {
            var cache = GlobalVarDA.Get("TodayExpedition");
            if (!string.IsNullOrEmpty(cache.Value))
            {
                var modelNames = JsonConvert.DeserializeObject<string[]>(cache.Value);
                return Scenes.Where(s => modelNames != null && modelNames.Contains(s.Name)).ToList();
            }

            var todayScenes = Rander.RandSort(Scenes.ToArray()).Take(3).ToList();
            cache.Value = JsonConvert.SerializeObject(todayScenes.Select(s => s.Name).ToArray());
            cache.ExpiryTime = CommonUtil.UntilTommorow();
            cache.Update();

            return todayScenes;
        }

        public Dictionary<string, int> RandFlavorings(int count)
        {
            var result = new Dictionary<string, int>();
            for (var i = 0; i < count; i++)
            {
                var randFlavoring = Flavorings.RandElement();
                if (result.ContainsKey(randFlavoring))
                {
                    result[randFlavoring]++;
                }
                else
                {
                    result.Add(randFlavoring, 1);
                }

                Thread.Sleep(10);
            }

            return result;
        }

        public (bool canView, string viewCommand) ViewableCheck(string name)
        {
            return this[name] == null ? (false, null) : (true, "查看远征地点");
        }
    }
}